package com.zhaoyd.redislock.core.lock;

import com.zhaoyd.redislock.core.SimpleRedisClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * SyncLock工厂类
 * @author zhaoyd
 * @date 2020-05-21
 */
@Component
public class SyncLockFactory {
    @Resource
    private SimpleRedisClient simpleRedisClient;

    private Map<String,SyncLock> syncLockMap = new ConcurrentHashMap<>();

    /**
     * 创建SyncLock
     * 这里搞个类似单例的双重检查锁性能更好
     * @param key Redis key
     * @param expire Redis TTL/秒，默认10秒
     * @param safetyTime 安全时间/秒，为了防止程序异常导致死锁，在此时间后强制拿锁，默认 expire * 5 秒
     */
    public synchronized SyncLock build(String key,long expire, Long safetyTime){
        if (!syncLockMap.containsKey(key)) {
            syncLockMap.put(key, new SyncLock(key, simpleRedisClient, expire, safetyTime));
        }
        return syncLockMap.get(key);
    }
}
